//
//  GJFEditPersonViewController.m
//  Wedding
//
//  Created by 郭静芬 on 2017/1/11.
//  Copyright © 2017年 郭静芬. All rights reserved.
//

#import "GJFEditPersonViewController.h"
#import "GJFEditPersonModel.h"
#import "GJFEditPersonTableViewCell.h"
#import "GJFEditNameViewController.h"
#import "GJFEditSignBackViewController.h"
#import "HFPickerArea.h"

@interface GJFEditPersonViewController ()<UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate, HFPickerAreaDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *editPerArr;
@end

@implementation GJFEditPersonViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self refreshData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"个人信息";
    [self tableView];
}

- (void)refreshData {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"EditPersonList" ofType:@"plist"];
    self.editPerArr = [GJFEditPersonModel transformWithArr:[[NSArray alloc] initWithContentsOfFile:path]];
    [self.tableView reloadData];
}

#pragma mark - TableView的分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
#pragma mark - TableView每个分区中row数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.editPerArr.count;
    }
    return 1;
}

#pragma mark - TableView每个分区中row的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        GJFEditPersonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EditPerCell"];
        cell.model = self.editPerArr[indexPath.row];
        return cell;
    }
    else {
        return nil;
    }
}
#pragma mark - TableView每个分区中cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
            return 80 * YY;
    }
    return 44 * YY;
}
#pragma mark - TableView每个分区头部的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
        return 20 * YY;
    
}
#pragma mark - TableView每个分区尾部的高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}
#pragma mark - TableView点击跳转
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        // 编辑头像
        if (indexPath.row == 0) {
            [self editAvatar];
        }
        // 昵称/真实姓名
        else if (indexPath.row == 1 || indexPath.row == 2) {
            GJFEditNameViewController *editNameVC = [[GJFEditNameViewController alloc] init];
            editNameVC.editPersonStyle = indexPath.row < 2 ? EditPersonStyleNickname :EditPersonStyleRealname;
            [self.navigationController pushViewController:editNameVC animated:YES];
        }
        // 性别
        else if (indexPath.row == 3) {
            [self editSex];
        }
        else if (indexPath.row == 5) {
            HFPickerArea *pickerArea = [[HFPickerArea alloc]init];
            pickerArea.delegate = self;
            [pickerArea setContentMode:STPickerContentModeBottom];
            [pickerArea show];
        }
        // 个性签名
        else if (indexPath.row == 6) {
            GJFEditSignBackViewController *editSignVC = [[GJFEditSignBackViewController alloc] init];
            [self.navigationController pushViewController:editSignVC animated:YES];
        }
    }
}
#pragma mark - 编辑头像
- (void)editAvatar {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"请选择图片来源" preferredStyle: UIAlertControllerStyleActionSheet];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self photoFromCamera];
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self photoFromAlbum];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    [alertController addAction:photoAction];
    [alertController addAction:albumAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark - 从相机获取图片
- (void)photoFromCamera {
    
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;//设置类型为相机
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
        picker.delegate = self;//设置代理
        picker.allowsEditing = YES;//设置照片可编辑
        picker.sourceType = sourceType;
        //设置是否显示相机控制按钮 默认为YES
        picker.showsCameraControls = YES;
        //选择前置摄像头或后置摄像头
        picker.cameraDevice=UIImagePickerControllerCameraDeviceFront;
        [self presentViewController:picker animated:YES completion:^{
        }];
    }
    else {
        NSLog(@"该设备无相机");  
    }
}  
#pragma mark - 从相册获取图片
- (void)photoFromAlbum {
    //首先需要判断资源是否可用
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
        
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //获得相机模式下支持的媒体类型
        pickerImage.delegate = self;
        //设置允许编辑
        pickerImage.allowsEditing = YES;
        [self presentViewController:pickerImage animated:YES completion:^{
        }];
    }  
}  
#pragma mark - 选择图片后操作
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    //获取裁剪后的图像
    UIImage *image = info[UIImagePickerControllerEditedImage];
    [self getQnToken:image];
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}
#pragma mark - 上传图片
// -> 上传图片step1. 获取token
- (void)getQnToken:(UIImage *)image {
    [self.view showBusyHUD];
    [GJFNetworkTool POSTRequestWithUrl:APP_MINE_QINIUTOKEN params:nil complete:^(NSDictionary *result) {
        
        if ([[result objectForKey:@"code"] intValue] != 1000) {
            [self.view showWarning:@"更新图片失败"];
            return;
        }
        NSString *token = [result objectForKey:@"data"];
        [self uploadQnAction:image uploadToken:token];
        
    }];
}
// -> 上传图片step2. 上传图片到七牛,图片url
- (void)uploadQnAction:(UIImage *)image uploadToken:(NSString *)token {
    
    NSData *data = UIImageJPEGRepresentation(image, 0.01);
    QNUploadManager *upManager = [[QNUploadManager alloc] init];
    NSString *imageName = [[self getDateTimeString] stringByAppendingString:@".jpeg"];//20170508214405.jpeg
    [upManager putData:data key:imageName token:token
              complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                  if (!resp) {
                      [self.view showWarning:@"更新图片失败1"];
                      return;
                  }
                  [self updateAvaterAction:[resp objectForKey:@"key"]];
              } option:nil];
}
// -> 上传图片step3. 将图片url传给服务器
- (void)updateAvaterAction:(NSString *)imageName {
    NSString *imageUrl = [NSString stringWithFormat:@"%@%@", [GJFSingleTool shareInstance].userInfo.qn_baseUrl, imageName];
    NSDictionary *dict = @{@"avatar":imageUrl};
    [GJFNetworkTool POSTRequestWithUrl:APP_MINE_AVATAR params:dict complete:^(NSDictionary *result) {
        [self.view hideBusyHUD];
        
        if ([[result objectForKey:@"code"] intValue] != 1000) {
            [self.view showWarning:@"更新图片失败2"];
            return;
        }
        [self.view showWarning:@"上传成功"];
        [GJFSingleTool shareInstance].userInfo.avatar = imageUrl;
        [GJFSingleTool saveUserInfo];
        [self refreshData];
    }];
}
- (NSString *)getDateTimeString {
    
    NSDateFormatter* formatter;
    NSString* dateString;
    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd_HH_mm_ss"];
    dateString = [formatter stringFromDate:[NSDate date]];
    return dateString;
}

#pragma mark - 编辑性别
- (void)editSex {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"请选择您的性别" preferredStyle: UIAlertControllerStyleActionSheet];
    UIAlertAction *maleAction = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.view showBusyHUD];
        
        NSDictionary *dic = @{@"sex": @"男"};
        [GJFNetworkTool POSTRequestWithUrl:APP_MINE_SEX params:dic complete:^(NSDictionary *result) {
            [self.view hideBusyHUD];
            if ([result[@"code"] intValue] == 1000) {
                GJFUserInfo *userInfo = [GJFSingleTool shareInstance].userInfo;
                userInfo.sex = @"男";
                [GJFSingleTool saveUserInfo];
                [self refreshData];
            }
        }];
    }];
    UIAlertAction *femaleAction = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.view showBusyHUD];
        
        NSDictionary *dic = @{@"sex": @"女"};
        [GJFNetworkTool POSTRequestWithUrl:APP_MINE_SEX params:dic complete:^(NSDictionary *result) {
            [self.view hideBusyHUD];
            if ([result[@"code"] intValue] == 1000) {
                GJFUserInfo *userInfo = [GJFSingleTool shareInstance].userInfo;
                userInfo.sex = @"女";
                [GJFSingleTool saveUserInfo];
                [self refreshData];
            }
        }];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:maleAction];
    [alertController addAction:femaleAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
// 编辑地区
- (void)pickerArea:(HFPickerArea *)pickerArea province:(NSString *)province city:(NSString *)city {
    if (!kStringIsEmpty(province) && !kStringIsEmpty(city)) {
        [self.view showBusyHUD];
        NSDictionary *dict = @{@"prov":province, @"city":city};
        [GJFNetworkTool POSTRequestWithUrl:APP_MINE_AREA params:dict complete:^(NSDictionary *result) {
            [self.view hideBusyHUD];
            if ([result[@"code"] intValue] == 1000) {
                GJFUserInfo *userInfo = [GJFSingleTool shareInstance].userInfo;
                userInfo.city = city;
                userInfo.prov = province;
                [GJFSingleTool saveUserInfo];
                [self refreshData];
            }
            [self.view showWarning:result[@"msg"]];
        }];
    }
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        [_tableView registerClass:[GJFEditPersonTableViewCell class] forCellReuseIdentifier:@"EditPerCell"];
        
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
